package nl.hva.three2learn.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import nl.hva.three2learn.model.Post;
@Repository
public class PostDaoImpl implements PostDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Post findById(long postId) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Post p where p.id = :id");
		q.setLong("id", postId);
		
		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		if (result == null)
			return null;
		
		return (Post) result;
	}

	@Override
	public void save(Post post) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(post);
		session.getTransaction().commit();
	}

	@Override
	public void delete(Post post) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.delete(post);
		session.getTransaction().commit();
	}

}
